package com.china.config;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.china.mapper.ConversationMapper;
import com.china.pojo.Conversation;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MySqlChatMemory implements ChatMemory {

    @Autowired
    private ConversationMapper conversationMapper;

    /**
     * 保存到数据库     保存到conversation这张表
     * @param conversationId
     * @param messages
     */
    @Override
    public void add(String conversationId, List<Message> messages) {
        List<Conversation> list = messages.stream().map(m -> {
            return Conversation.builder()
                    .type(m.getMessageType().getValue())
                    .message(m.getText())
                    .createTime(LocalDateTime.now())
                    .conversationId(conversationId)
                    .build();
        }).toList();
        conversationMapper.insert(list);
    }

    /**
     * 查询对应的消息
     * @param conversationId
     * @return
     */
    @Override
    public List<Message> get(String conversationId) {
        //sql:clect * from conversation where  conversation_id = ?
        List<Conversation> conversations = conversationMapper.selectList(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId));
        List<Message> list = conversations.stream().map(c -> {
            Message message = null;
            if (MessageType.USER.getValue().equals(c.getType())) {
                //这个是用户消息
                message = new UserMessage(c.getMessage());
            } else if (MessageType.ASSISTANT.getValue().equals(c.getType())) {
                //这个是大模型的消息
                message = new AssistantMessage(c.getMessage());
            }
            return message;
        }).toList();
        return list;
    }
    /**
     * 删除对应的消息
     * @param conversationId
     */
    @Override
    public void clear(String conversationId) {
        conversationMapper.delete(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId));
    }
}
